<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="false" label-position="left" label-width="80px">
        <el-row :gutter="20">
          <el-col :lg="6" :md="8" :sm="12">
            <el-form-item label="院校名称" prop="collegeName">
              <el-input
                v-model="queryParams.collegeName"
                placeholder="请输入院校名称"
                clearable
                prefix-icon="el-icon-reading"
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12">
            <el-form-item label="院校代码" prop="collegeNo">
              <el-input
                v-model="queryParams.collegeNo"
                placeholder="请输入院校代码"
                clearable
                prefix-icon="el-icon-school"
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12">
            <el-form-item label="所在城市" prop="city">
              <el-input
                v-model="queryParams.city"
                placeholder="请输入城市"
                clearable
                prefix-icon="el-icon-position"
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
           <el-col :lg="6" :md="8" :sm="12">
            <el-form-item label="院校层次" prop="collegeLevel">
              <el-select v-model="queryParams.collegeLevel" placeholder="请选择层次" clearable size="small" style="width: 100%;">
                <el-option
                  v-for="item in levelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12">
            <el-form-item label="院校类型" prop="collegeType">
               <el-select v-model="queryParams.collegeType" placeholder="请选择类型" clearable size="small" style="width: 100%;">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                   <span style="float: left">{{ item.label }}</span>
                   <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="8" :sm="12">
             <!-- 搜索按钮区域，通过 offset 推到右侧 -->
            <el-form-item label-width="0px"> 
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 图表统计区域 -->
    <el-card class="chart-card" shadow="hover">
      <div class="card-title">
        <span><i class="el-icon-pie-chart"></i> 院校数据统计</span>
        <el-switch
          v-model="showCharts"
          active-text="显示图表"
          inactive-text="隐藏图表"
        />
      </div>
      <div v-show="showCharts" class="chart-container">
        <el-row :gutter="20">
          <el-col :lg="12" :md="24">
            <div id="cityDistributionChart" class="chart"></div>
          </el-col>
          <el-col :lg="12" :md="24">
            <div id="rankingDistributionChart" class="chart"></div>
          </el-col>
          <el-col :lg="12" :md="24">
            <div id="levelDistributionChart" class="chart"></div>
          </el-col>
           <el-col :lg="12" :md="24">
            <div id="typeDistributionChart" class="chart"></div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="hover">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['entrance:college:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['entrance:college:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['entrance:college:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-data-analysis"
            size="mini"
            @click="goToAnalysis"
          >高校分析
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <el-table 
        v-loading="loading" 
        :data="collegeList" 
        @selection-change="handleSelectionChange"
        border
        stripe
        highlight-current-row
        :header-cell-style="{backgroundColor: '#f5f7fa', color: '#303133', fontWeight: 'bold'}"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="院校代码" prop="collegeNo" :show-overflow-tooltip="true" width="100">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.collegeNo" placement="top">
              <span>
                <i class="el-icon-school" style="margin-right: 5px; color: #409EFF;"></i>
                {{ scope.row.collegeNo }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="院校名称" prop="collegeName" :show-overflow-tooltip="true" min-width="120">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.collegeName" placement="top">
              <span class="college-name">
                {{ scope.row.collegeName }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="城市" prop="city" :show-overflow-tooltip="true" width="100" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" type="info" effect="plain" v-if="scope.row.city">
              <i class="el-icon-position"></i> {{ scope.row.city }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="排名" prop="ranking" :show-overflow-tooltip="true" width="100" align="center" sortable>
          <template slot-scope="scope">
            <el-tag size="mini" :type="getRankingTagType(scope.row.ranking)" v-if="scope.row.ranking">
              {{ scope.row.ranking }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="人数" prop="personCount" :show-overflow-tooltip="true" width="100" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" type="success" v-if="scope.row.personCount">
              {{ scope.row.personCount }}人
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="详情" prop="detailInfo" :show-overflow-tooltip="true" min-width="200">
          <template slot-scope="scope">
            <div class="detail-info-text" v-if="scope.row.detailInfo">
              {{ scope.row.detailInfo }}
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdTime" width="160">
          <template slot-scope="scope">
            <i class="el-icon-time" style="margin-right: 5px; color: #909399;"></i>
            <span>{{ parseTime(scope.row.createdTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope" v-if="scope.row.id !== 0">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              circle
              @click="handleUpdate(scope.row)"
              v-hasPermi="['entrance:college:edit']"
              title="修改"
            />
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              circle
              @click="handleDelete(scope.row)"
              v-hasPermi="['entrance:college:remove']"
              title="删除"
            />
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="院校代码" prop="collegeNo">
              <el-input v-model="form.collegeNo" placeholder="请输入院校代码" prefix-icon="el-icon-school" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="院校名称" prop="collegeName">
              <el-input v-model="form.collegeName" placeholder="请输入院校名称" prefix-icon="el-icon-reading" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-input v-model="form.city" placeholder="请输入城市" prefix-icon="el-icon-position" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排名" prop="ranking">
              <el-input-number
                v-model="form.ranking"
                :precision="0"
                :step="1"
                :min="1"
                placeholder="请输入排名"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人数" prop="personCount">
              <el-input-number
                v-model="form.personCount"
                :precision="0"
                :step="10"
                :min="0"
                placeholder="请输入人数"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详情" prop="detailInfo">
          <el-input
            type="textarea"
            v-model="form.detailInfo"
            placeholder="请输入院校详情"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCollege, getCollege, addCollege, updateCollege, delCollege } from "@/api/entrance/college";
import * as echarts from 'echarts';

const MOCK_COLLEGE_KEY = 'mockCollegeData'; // sessionStorage key
const MOCK_COUNT = 700; // 定义要生成的模拟数据量 (从 250 增加到 700)

// 将模拟数据生成逻辑提取到组件外部或 methods 中，避免重复定义
function generateMockCollegeData() {
    console.log("Generating new mock college data...");
    const mockList = [];
    const levels = ['985工程', '211工程', '双一流', '普通本科', '专科', '普通本科', '普通本科'];
    const types = ['综合', '理工', '师范', '医药', '财经', '农林', '政法', '艺术', '体育', '民族', '理工', '综合'];
    const cities = ['北京', '上海', '广州', '深圳', '杭州', '南京', '武汉', '成都', '西安', '重庆', '天津', '苏州', '长沙', '郑州', '沈阳'];
    const namePrefixes = ['模拟', '示例', '测试', '演示', '虚拟'];
    const nameSuffixes = ['大学', '学院', '工业大学', '科技大学', '师范学院', '医科大学', '财经学院', '职业技术学院'];

    for (let i = 1; i <= MOCK_COUNT; i++) {
        const ranking = Math.random() < 0.05 ? null : Math.floor(Math.random() * 600) + 1;
        const city = cities[Math.floor(Math.random() * cities.length)];
        let level = '普通本科';
        if (ranking) {
            if (ranking <= 30) level = '985工程';
            else if (ranking <= 112) level = '211工程';
            else if (ranking <= 150 && Math.random() < 0.7) level = '双一流';
            else if (ranking > 500 && Math.random() < 0.4) level = '专科';
        } else {
            level = levels[Math.floor(Math.random() * levels.length)];
        }

        let type = types[Math.floor(Math.random() * types.length)];
        if (level === '专科' && ['985工程', '211工程'].includes(level)) type = '综合'; 
        if ((level === '985工程' || level === '211工程') && ['艺术', '体育', '民族'].includes(type) && Math.random() < 0.8) type = '综合';

        const name = `${namePrefixes[i % namePrefixes.length]}${city}${type}${nameSuffixes[i % nameSuffixes.length]}${i}`;

        mockList.push({
            id: 1000 + i,
            collegeNo: `M${10000 + i}`,
            collegeName: name,
            city: city,
            ranking: ranking,
            personCount: Math.floor(Math.random() * 25000) + 3000,
            detailInfo: `${name} 的模拟详细介绍，位于美丽的 ${city}，是一所优秀的 ${level} ${type} 院校。成立于 ${1950 + (i % 70)} 年。`,
            createdTime: new Date(Date.now() - Math.floor(Math.random() * 1000 * 3600 * 24 * 90)).toISOString(),
            collegeLevel: level,
            collegeType: type,
            status: Math.floor(Math.random() * 3)
        });
    }
    // 存入 sessionStorage
    try {
       sessionStorage.setItem(MOCK_COLLEGE_KEY, JSON.stringify(mockList));
    } catch (e) {
       console.error("Failed to save mock data to sessionStorage:", e);
    }
    return mockList;
}

export default {
  name: "College",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 院校表格数据
      collegeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        collegeNo: undefined,
        collegeName: undefined,
        city: undefined,
        collegeLevel: undefined,
        collegeType: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        collegeNo: [
          { required: true, message: "院校代码不能为空", trigger: "blur" }
        ],
        collegeName: [
          { required: true, message: "院校名称不能为空", trigger: "blur" }
        ],
        city: [
          { required: true, message: "城市不能为空", trigger: "blur" }
        ]
      },
      // 图表相关
      showCharts: true,
      cityDistributionChart: null,
      rankingDistributionChart: null,
      levelDistributionChart: null,
      typeDistributionChart: null,
      // 新增：筛选选项
      levelOptions: [
        { value: '985', label: '985工程' },
        { value: '211', label: '211工程' },
        { value: '双一流', label: '双一流' },
        { value: '普通本科', label: '普通本科' },
        { value: '专科', label: '专科' },
      ],
      typeOptions: [
        { value: '综合', label: '综合类' },
        { value: '理工', label: '理工类' },
        { value: '师范', label: '师范类' },
        { value: '医药', label: '医药类' },
        { value: '财经', label: '财经类' },
        { value: '农林', label: '农林类' },
        { value: '政法', label: '政法类' },
        { value: '艺术', label: '艺术类' },
        { value: '体育', label: '体育类' },
        { value: '民族', label: '民族类' },
        { value: '军事', label: '军事类' },
        { value: '其他', label: '其他' },
      ],
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.initCharts();
  },
  beforeDestroy() {
    // 在组件销毁前移除窗口大小变化的监听
    window.removeEventListener('resize', this.resizeCharts);
  },
  methods: {
    /** 获取或生成模拟数据 */
    getOrGenerateMockData() {
      try {
        const storedData = sessionStorage.getItem(MOCK_COLLEGE_KEY);
        if (storedData) {
          console.log("Loading mock data from sessionStorage...");
          return JSON.parse(storedData);
        }
      } catch (e) {
         console.error("Failed to load mock data from sessionStorage:", e);
         // 如果解析失败，清除可能损坏的数据
         sessionStorage.removeItem(MOCK_COLLEGE_KEY);
      }
      // 如果 sessionStorage 中没有或加载失败，则生成新的
      return generateMockCollegeData();
    },

    /** 查询院校列表 (修改为使用 sessionStorage 和前端筛选分页) */
    getList() {
      this.loading = true;
      
      // 1. 获取完整的模拟数据列表
      const fullMockList = this.getOrGenerateMockData();

      // 2. 根据 queryParams 在前端进行筛选
      const { collegeName, collegeNo, city, collegeLevel, collegeType } = this.queryParams;
      let filteredList = fullMockList.filter(item => {
          if (collegeName && item.collegeName && !item.collegeName.toLowerCase().includes(collegeName.toLowerCase())) {
              return false;
          }
          if (collegeNo && item.collegeNo && !item.collegeNo.toLowerCase().includes(collegeNo.toLowerCase())) {
              return false;
          }
          if (city && item.city && !item.city.toLowerCase().includes(city.toLowerCase())) {
              return false;
          }
          if (collegeLevel && item.collegeLevel !== collegeLevel) {
              return false;
          }
          if (collegeType && item.collegeType !== collegeType) {
              return false;
          }
          return true;
      });

      // 3. 更新总数 (筛选后的总数)
      this.total = filteredList.length;

      // 4. 根据 queryParams 在前端进行分页
      const { pageNum, pageSize } = this.queryParams;
      const start = (pageNum - 1) * pageSize;
      const end = start + pageSize;
      const paginatedList = filteredList.slice(start, end);

      // 5. 更新表格数据
      this.collegeList = paginatedList;
      this.loading = false;
      
      // 6. 更新图表 (基于筛选和分页后的数据，或者可以选择基于 filteredList 更新)
      this.$nextTick(() => {
          // 注意：图表现在反映的是当前页的数据，如果希望反映筛选后全部数据，应传入 filteredList 去统计
          this.updateCharts(); 
      });

      // --- 注释掉原有的 API 调用和模拟数据生成 --- 
      /* ... */
    },
    // 获取排名标签类型
    getRankingTagType(ranking) {
      if (!ranking) return '';
      if (ranking <= 50) return 'danger';
      if (ranking <= 100) return 'warning';
      if (ranking <= 200) return 'success';
      return 'info';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        collegeNo: undefined,
        collegeName: undefined,
        ranking: undefined,
        personCount: undefined,
        city: undefined,
        detailInfo: undefined
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加院校";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const collegeId = row.id || this.ids
      getCollege(collegeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改院校";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateCollege(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.$message.error("修改失败");
            });
          } else {
            addCollege(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.$message.error("新增失败");
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const collegeIds = row.id || this.ids;
      this.$confirm('是否确认删除院校ID为"' + collegeIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delCollege(collegeIds);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
    /** 初始化图表 */
    initCharts() {
      this.$nextTick(() => {
        // 初始化城市分布图
        const cityChartDom = document.getElementById('cityDistributionChart');
        if (cityChartDom) {
          this.cityDistributionChart = echarts.init(cityChartDom);
        }
        
        // 初始化排名分布图
        const rankingChartDom = document.getElementById('rankingDistributionChart');
        if (rankingChartDom) {
          this.rankingDistributionChart = echarts.init(rankingChartDom);
        }
        
        // 初始化层次分布图
        const levelChartDom = document.getElementById('levelDistributionChart');
        if (levelChartDom) {
          this.levelDistributionChart = echarts.init(levelChartDom);
        }
        
        // 初始化类型分布图
        const typeChartDom = document.getElementById('typeDistributionChart');
        if (typeChartDom) {
          this.typeDistributionChart = echarts.init(typeChartDom);
        }
        
        // 窗口大小改变时，重新调整图表大小
        window.addEventListener('resize', this.resizeCharts);
        
        // 首次更新图表
        this.updateCharts();
      });
    },
    
    /** 重新调整图表大小 */
    resizeCharts() {
      if (this.cityDistributionChart) {
        this.cityDistributionChart.resize();
      }
      if (this.rankingDistributionChart) {
        this.rankingDistributionChart.resize();
      }
      if (this.levelDistributionChart) {
        this.levelDistributionChart.resize();
      }
      if (this.typeDistributionChart) {
        this.typeDistributionChart.resize();
      }
    },
    
    /** 更新图表数据 */
    updateCharts() {
      if (!this.collegeList || this.collegeList.length === 0) {
         console.warn("No college data to update charts.");
         return;
      }
      if (!this.cityDistributionChart || !this.rankingDistributionChart || !this.levelDistributionChart || !this.typeDistributionChart) {
          console.warn("Charts not initialized yet.");
          return;
      }
      
      this.updateCityDistributionChart();
      this.updateRankingDistributionChart();
      this.updateLevelDistributionChart();
      this.updateTypeDistributionChart();
    },
    
    /** 更新城市分布图 */
    updateCityDistributionChart() {
      if (!this.cityDistributionChart) return;
      
      // 统计城市分布数据
      const cityMap = {};
      this.collegeList.forEach(item => {
        if (item.city) {
          if (cityMap[item.city]) {
            cityMap[item.city]++;
          } else {
            cityMap[item.city] = 1;
          }
        }
      });
      
      // 转换为图表数据格式
      const data = Object.keys(cityMap).map(city => ({
        name: city,
        value: cityMap[city]
      }));
      
      // 排序并截取前10个城市
      data.sort((a, b) => b.value - a.value);
      const topCities = data.slice(0, 10);
      
      const option = {
        title: {
          text: '院校城市分布Top10',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          type: 'scroll',
          data: topCities.map(item => item.name)
        },
        series: [
          {
            name: '城市分布',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: topCities,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      this.cityDistributionChart.setOption(option);
    },
    
    /** 更新排名分布图 */
    updateRankingDistributionChart() {
      if (!this.rankingDistributionChart) return;
      
      // 定义排名区间
      const rankingRanges = [
        { name: '前50名', min: 1, max: 50, count: 0 },
        { name: '51-100名', min: 51, max: 100, count: 0 },
        { name: '101-200名', min: 101, max: 200, count: 0 },
        { name: '201-300名', min: 201, max: 300, count: 0 },
        { name: '300名以后', min: 301, max: Infinity, count: 0 },
        { name: '未排名', min: 0, max: 0, count: 0 }
      ];
      
      // 调试信息
      console.log('院校总数:', this.collegeList.length);
      
      // 统计排名分布
      this.collegeList.forEach(item => {
        if (!item.ranking) {
          rankingRanges[5].count++; // 未排名
        } else if (item.ranking <= 50) {
          rankingRanges[0].count++; // 前50名
        } else if (item.ranking <= 100) {
          rankingRanges[1].count++; // 51-100名
        } else if (item.ranking <= 200) {
          rankingRanges[2].count++; // 101-200名
        } else if (item.ranking <= 300) {
          rankingRanges[3].count++; // 201-300名
        } else {
          rankingRanges[4].count++; // 300名以后
        }
      });
      
      // 调试信息
      console.log('排名分布统计:', rankingRanges);
      
      const option = {
        title: {
          text: '院校排名分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: rankingRanges.map(item => item.name)
        },
        yAxis: {
          type: 'value',
          name: '院校数量'
        },
        series: [
          {
            name: '院校数量',
            type: 'bar',
            data: rankingRanges.map(item => ({
              value: item.count,
              itemStyle: {
                color: this.getRankingBarColor(item.name)
              }
            })),
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      };
      
      this.rankingDistributionChart.setOption(option);
    },
    
    /** 根据排名获取柱状图颜色 */
    getRankingBarColor(rankName) {
      const colorMap = {
        '前50名': '#F56C6C',
        '51-100名': '#E6A23C',
        '101-200名': '#67C23A',
        '201-300名': '#409EFF',
        '300名以后': '#909399',
        '未排名': '#DCDFE6'
      };
      return colorMap[rankName] || '#409EFF';
    },
    // 前往院校分析
    goToAnalysis() {
      this.$router.push('/entrance/college/analysis/index');
    },
    /** 更新院校层次分布图 (新增) */
    updateLevelDistributionChart() {
      if (!this.levelDistributionChart) return;
      
      const levelMap = {};
      this.levelOptions.forEach(opt => { levelMap[opt.value] = 0; }); 
      levelMap['其他'] = 0; // 保持'其他'类别以防万一

      this.collegeList.forEach(item => {
        const level = item.collegeLevel; 
        if (level && levelMap.hasOwnProperty(level)) {
          levelMap[level]++;
        } else {
          levelMap['其他']++; // 未在 levelOptions 定义的归入其他
        }
      });

      const data = Object.keys(levelMap)
                         .filter(key => levelMap[key] > 0) 
                         .map(key => ({ name: key, value: levelMap[key] }));

      const option = {
        title: { text: '院校层次分布', left: 'center' },
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {c} ({d}%)' },
        legend: { orient: 'vertical', left: 'left', type: 'scroll' },
        color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'], // 添加调色盘
        series: [
          {
            name: '层次分布',
            type: 'pie',
            radius: ['30%', '65%'], // 改为环状图，增加视觉效果
            center: ['50%', '60%'],
            roseType: 'area', // 使用 roseType
             itemStyle: { // 添加圆角效果
               borderRadius: 5,
               borderColor: '#fff',
               borderWidth: 1
            },
            label: { // 优化标签显示
                show: true,
                formatter: '{b}: {d}%'
            },
            labelLine: {
                show: true,
                length: 5,
                length2: 10
            },
            data: data,
            emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }
          }
        ]
      };
      this.levelDistributionChart.setOption(option);
    },
    
    /** 更新院校类型分布图 (新增) */
    updateTypeDistributionChart() {
      if (!this.typeDistributionChart) return;
      
      const typeMap = {};
      // 基于 typeOptions 初始化，确保 key 存在
      this.typeOptions.forEach(opt => { typeMap[opt.value] = 0; });
      typeMap['未知'] = 0; 
      if(!typeMap['语言']) typeMap['语言'] = 0; // 确保模拟数据中的'语言'有地方放
      if(!typeMap['军事']) typeMap['军事'] = 0;

      this.collegeList.forEach(item => {
        const type = item.collegeType;
        if (type && typeMap.hasOwnProperty(type)) {
          typeMap[type]++;
        } else {
          typeMap['未知']++;
        }
      });

      const data = Object.keys(typeMap)
                         .filter(key => typeMap[key] > 0)
                         .map(key => ({ name: key, value: typeMap[key] }));

      const option = {
        title: { text: '院校类型分布', left: 'center' },
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {c} ({d}%)' },
        legend: { orient: 'vertical', left: 'left', type: 'scroll' },
        color: ['#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#5470c6', '#91cc75', '#a7d28e', '#d87c7c', '#8d98b3' ], // 不同调色盘
        series: [
          {
            name: '类型分布',
            type: 'pie',
            radius: ['30%', '65%'], // 环状图
            center: ['50%', '60%'],
            roseType: 'radius', // 另一种 roseType
             itemStyle: {
               borderRadius: 5,
               borderColor: '#fff',
               borderWidth: 1
            },
            label: { 
                show: true, 
                formatter: '{b|{b}}\n{hr|}\n{c|{c}所 ({d}%)}',
                rich: { // 使用富文本标签
                    b: { fontSize: 12, lineHeight: 18 },
                    hr: { borderColor: '#aaa', width: '100%', borderWidth: 0.5, height: 0 },
                    c: { fontSize: 11, lineHeight: 16, color: '#666' }
                }
            },
            labelLine: {
                show: true,
                length: 5,
                length2: 15
            },
            data: data,
            emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }
          }
        ]
      };
      this.typeDistributionChart.setOption(option);
    },
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-card,
  .action-card,
  .table-card,
  .chart-card {
    margin-bottom: 20px;
    border-radius: 5px;
    
    ::v-deep .el-card__header {
      padding: 12px 20px;
      font-weight: bold;
    }
    
    ::v-deep .el-card__body {
      padding: 15px 20px;
    }
  }
  
  .college-name {
    font-weight: 500;
    color: #303133;
  }
  
  .detail-info-text {
    color: #606266;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }
  
  ::v-deep .el-table {
    .el-button--mini.is-circle {
      padding: 7px;
    }
    
    th {
      background-color: #f5f7fa !important;
    }
    
    td {
      padding: 8px 0;
    }
  }
  
  /** 表格tips宽度样式*/
  ::v-deep .el-tooltip__popper {
    max-width: 800px;
  }
  
  .chart-card {
    .card-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;
      
      span {
        font-size: 16px;
        font-weight: bold;
        
        i {
          margin-right: 5px;
          color: #409EFF;
        }
      }
    }
    
    .chart-container {
      margin-top: 20px;
      
      .chart {
        height: 300px;
        margin-bottom: 20px;
      }
    }
  }
}

.search-card {
  .el-form {
    // 移除 inline 相关的默认样式影响 (如果之前设置了)
  }
  .el-form-item {
    margin-bottom: 18px; // 统一 form item 间距
  }
  // 确保选择器宽度正确
  .el-select {
    width: 100%;
  }
}
</style>

